import React, { useState, useEffect } from 'react';
import { Card, Statistic, Row, Col, List, Avatar, Tag, Typography, Spin } from 'antd';
import {
  DatabaseOutlined,
  QrcodeOutlined,
  FileExcelOutlined,
  UserOutlined,
  ClockCircleOutlined,
  LaptopOutlined,
  DatabaseOutlined as ServerOutlined,
  CloudOutlined
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { fetchDevices } from '../redux/features/deviceSlice';
import './Dashboard.css';

const { Title, Paragraph } = Typography;
const { Meta } = Card;

const Dashboard = () => {
  const dispatch = useDispatch();
  const { userInfo } = useSelector((state) => state.user);
  const { devices, isLoading } = useSelector((state) => state.device);
  
  const [dashboardStats, setDashboardStats] = useState({
    deviceCount: 0,
    qrCodeGeneratedCount: 0,
    todayOperations: 0,
    onlineUsers: 0,
    deviceTypeStats: [],
    recentActivities: []
  });

  useEffect(() => {
    // 获取设备列表数据
    dispatch(fetchDevices());
  }, [dispatch]);

  useEffect(() => {
    if (devices && devices.length > 0) {
      // 计算设备统计数据
      const deviceCount = devices.length;
      const qrCodeGeneratedCount = devices.filter(device => device.qrcodeUrl).length;
      
      // 计算设备类型分布
      const deviceTypeCounts = {};
      devices.forEach(device => {
        deviceTypeCounts[device.deviceType] = (deviceTypeCounts[device.deviceType] || 0) + 1;
      });
      
      const deviceTypeStats = Object.entries(deviceTypeCounts).map(([name, value]) => ({
        name,
        value,
        icon: getDeviceTypeIcon(name)
      }));

      // 生成最近活动数据（基于设备创建时间）
      const recentActivities = [...devices] // 创建可修改的数组副本
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
        .slice(0, 5)
        .map((device, index) => ({
          id: index + 1,
          user: userInfo?.name || '用户',
          action: '创建',
          device: `${device.deviceName}-${device.deviceCode}`,
          time: formatDateTime(device.createdAt),
          avatar: userInfo?.name?.charAt(0) || '用'
        }));

      setDashboardStats({
        deviceCount,
        qrCodeGeneratedCount,
        todayOperations: Math.floor(Math.random() * 20) + 10, // 模拟今日操作次数
        onlineUsers: Math.floor(Math.random() * 5) + 1, // 模拟在线用户数
        deviceTypeStats,
        recentActivities
      });
    }
  }, [devices, userInfo]);

  // 根据设备类型获取图标
  const getDeviceTypeIcon = (deviceType) => {
    switch (deviceType) {
      case '服务器':
        return <ServerOutlined className="stat-icon" />;
      case '网络设备':
        return <CloudOutlined className="stat-icon" />;
      case '终端设备':
        return <LaptopOutlined className="stat-icon" />;
      default:
        return <DatabaseOutlined className="stat-icon" />;
    }
  };

  // 格式化日期时间
  const formatDateTime = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
  };

  // 格式化日期的辅助函数
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
  };

  // 根据操作类型获取标签颜色
  const getActionTagColor = (action) => {
    switch (action) {
      case '创建':
        return 'green';
      case '更新':
        return 'blue';
      case '删除':
        return 'red';
      case '生成二维码':
        return 'purple';
      case '导出':
        return 'orange';
      default:
        return 'default';
    }
  };

  if (isLoading) {
    return (
      <div className="dashboard-container" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '400px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className="dashboard-container">
      <div className="dashboard-header">
        <Title level={3} className="dashboard-title">
          欢迎使用设备二维码管理系统
        </Title>
        <Paragraph className="dashboard-subtitle">
          {userInfo?.name || userInfo?.phone || '用户'}，今天是 {formatDate(new Date())}，
          祝您工作愉快！
        </Paragraph>
      </div>

      {/* 统计卡片区域 */}
      <Row gutter={[16, 16]} className="stat-cards-row">
        <Col xs={24} sm={12} lg={6}>
          <Card className="stat-card">
            <Meta
              avatar={<Avatar icon={<DatabaseOutlined className="stat-icon-large" />} />}
              title="设备总数"
              description={
                  <Statistic 
                    value={devices.length} 
                    valueStyle={{ color: '#1890ff' }} 
                    prefix=""
                    suffix="台"
                  />
                }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="stat-card">
            <Meta
              avatar={<Avatar icon={<QrcodeOutlined className="stat-icon-large" />} />}
              title="已生成二维码"
              description={
                  <Statistic 
                    value={dashboardStats.qrCodeGeneratedCount} 
                    valueStyle={{ color: '#52c41a' }} 
                    prefix=""
                    suffix="台"
                  />
                }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="stat-card">
            <Meta
              avatar={<Avatar icon={<FileExcelOutlined className="stat-icon-large" />} />}
              title="今日操作次数"
              description={
                <Statistic 
                  value={dashboardStats.todayOperations} 
                  valueStyle={{ color: '#faad14' }} 
                  prefix=""
                  suffix="次"
                />
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="stat-card">
            <Meta
              avatar={<Avatar icon={<UserOutlined className="stat-icon-large" />} />}
              title="当前在线用户"
              description={
                <Statistic 
                  value={dashboardStats.onlineUsers} 
                  valueStyle={{ color: '#f5222d' }} 
                  prefix=""
                  suffix="人"
                />
              }
            />
          </Card>
        </Col>
      </Row>

      {/* 设备类型分布和最近活动 */}
      <Row gutter={[16, 16]} className="dashboard-content-row">
        <Col xs={24} lg={12}>
          <Card title="设备类型分布" className="dashboard-card">
            <Row gutter={[16, 16]}>
              {dashboardStats.deviceTypeStats.map((stat) => (
                <Col xs={12} sm={6} key={stat.name}>
                  <Card className="device-type-card">
                    <div className="device-type-content">
                      {stat.icon}
                      <div className="device-type-info">
                        <div className="device-type-name">{stat.name}</div>
                        <div className="device-type-value">{stat.value} 台</div>
                      </div>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="最近活动" className="dashboard-card">
            <List
              className="activity-list"
              itemLayout="horizontal"
              dataSource={dashboardStats.recentActivities}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar>{item.avatar}</Avatar>}
                    title={
                      <div className="activity-title">
                        <span>{item.user}</span>
                        <span> </span>
                        <Tag color={getActionTagColor(item.action)}>{item.action}</Tag>
                        <span> </span>
                        <span>{item.device}</span>
                      </div>
                    }
                    description={
                      <div className="activity-time">
                        <ClockCircleOutlined className="time-icon" />
                        {item.time}
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {/* 快速操作区域 */}
      <div className="quick-actions">
        <Card title="快速操作" className="dashboard-card">
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={12} md={6}>
              <Card className="quick-action-card" hoverable>
                <div className="quick-action-content">
                  <QrcodeOutlined className="quick-action-icon" />
                  <div className="quick-action-text">生成二维码</div>
                </div>
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card className="quick-action-card" hoverable>
                <div className="quick-action-content">
                  <DatabaseOutlined className="quick-action-icon" />
                  <div className="quick-action-text">创建设备</div>
                </div>
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card className="quick-action-card" hoverable>
                <div className="quick-action-content">
                  <FileExcelOutlined className="quick-action-icon" />
                  <div className="quick-action-text">导出数据</div>
                </div>
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card className="quick-action-card" hoverable>
                <div className="quick-action-content">
                  <LaptopOutlined className="quick-action-icon" />
                  <div className="quick-action-text">设备列表</div>
                </div>
              </Card>
            </Col>
          </Row>
        </Card>
      </div>
    </div>
  );
};

export default Dashboard;